package com.alibaba.citrus.cr.platform.enhance.repository.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerAddressRelationRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerAddressRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.CustomerRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.ScItemGroupRepository;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.page.PageResult;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.esdegrade.dto.GetEsDegradeValueResponse;
import com.epoch.app.bcorder.esdegrade.service.EsDegradeService;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.channel.service.ChannelService;
import com.epoch.app.crplatformenhance.domain.customer.model.Customer;
import com.epoch.app.crplatformenhance.domain.customeraddress.dto.*;
import com.epoch.app.crplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.crplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.crplatformenhance.domain.customersalescope.model.CustomerSaleScope;
import com.epoch.app.crplatformenhance.domain.scitemgroup.dto.LoadScItemGroupListRequest;
import com.epoch.app.crplatformenhance.domain.scitemgroup.model.ScItemGroup;
import com.epoch.app.crplatformenhance.domain.scitemgroup.service.ScItemGroupService;
import com.epoch.app.crplatformenhance.dto.feature.FullOrganizationValue;
import com.epoch.app.crplatformenhance.dto.request.CustomerAddressBatchRequest;
import com.epoch.app.crplatformenhance.dto.request.CustomerAddressRequest;
import com.epoch.app.crplatformenhance.dto.request.CustomerBatchRequest;
import com.epoch.app.crplatformenhance.dto.request.QueryAddressRequest;
import com.epoch.app.crplatformenhance.dto.request.QueryScItemGroupRequest;
import com.epoch.app.crplatformenhance.dto.request.SimpleQueryAddressRequest;
import com.epoch.app.crplatformenhance.enums.CommOperateTypeEnum;
import com.epoch.app.crplatformenhance.model.dto.ChannelResponse;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressIndex;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressRelationLoadListRequest;
import com.epoch.app.crplatformenhance.model.dto.CustomerAddressRelationSDO;
import com.epoch.app.crplatformenhance.model.dto.QueryChannelRequest;
import com.epoch.app.crplatformenhance.model.enums.CustomerRelationBizTypeEnum;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListNotPrincipalRequest;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListNotPrincipalResponse;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListRequest;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListResponse;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListWithPrincipalRequest;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.dto.PageQueryCustomerAddressListWithPrincipalResponse;
import com.epoch.app.crplatformenhance.opecustomeraddressindex.service.OpeCustomerAddressIndexService;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.crplatformenhance.sdo.CustomerSDO;
import com.epoch.app.crplatformenhance.sdo.ScItemGroupSDO;
import com.epoch.app.crpricecenter.model.dto.CustomerItemPriceRequest;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

@Component
public class CustomerAddressRepositoryImpl implements CustomerAddressRepository {
    private static final Log log = Log.getLogger(CustomerAddressRepositoryImpl.class);

    @Resource
    CustomerAddressService customerAddressService;

    @Resource
    ChannelService channelService;

    @Resource
    ScItemGroupService scItemGroupService;

    @Resource
    private OpeCustomerAddressIndexService addressIndexService;

    @Resource
    private BaseDataService baseDataService;

    @Resource
    private UnifiedInventoryService unifiedInventoryService;

    @Resource
    private CustomerRepository customerRepository;

    @Resource
    CustomerAddressRelationRepository customerAddressRelationRepository;

    @Resource
    EsDegradeService esDegradeService;

    @Override
    public Boolean editAddress(CustomerAddressSDO addressSDO) {
        CustomerAddress request = new CustomerAddress();
        BeanUtils.copyProperties(addressSDO, request);
        Set<String> platform = new HashSet<>();
        if (StringUtils.isNotBlank(addressSDO.getCommercePlatform())) {
            List<PlatformSDO> queryPlatforms1 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(addressSDO.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(queryPlatforms1)) {
                for (PlatformSDO platformSDO : queryPlatforms1) {
                    platform.add(platformSDO.getPlatformName());
                }
            }
            //判断传入的是否是页面回显的中文
            if (platform.contains(addressSDO.getCommercePlatform())) {
                List<PlatformSDO> queryPlatforms2 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformNames(Lists.newArrayList(addressSDO.getCommercePlatform())).build()).getResult();
                String platformCode1 = queryPlatforms2.get(0).getPlatformCode();
                request.setCommercePlatform(platformCode1);
            } else {
                //如果不包含说明传入的重选的id  那么就根据id去查询就可以
                List<PlatformSDO> queryPlatforms3 = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(addressSDO.getCommercePlatform())).build()).getResult();
                String platformCode2 = queryPlatforms3.get(0).getPlatformCode();
                request.setCommercePlatform(platformCode2);
            }
        } else {
            //如果在编辑的时候 把电商平台去除了 那么就滞空进行修改
            request.setCommercePlatform("");
        }

        //如果在分派或导入时  负责人为空 则置为空值 进行修改
        if (StringUtils.isBlank(addressSDO.getPrincipal())) {
            request.setPrincipal("");
        }
        //如果在分派或导入时  客户方负责人为空 则置为空值 进行修改
//        if (StringUtils.isBlank(addressSDO.getCustomerPrincipal())) {
//            request.setCustomerPrincipal("");
//        }

        request.setId(Long.parseLong(addressSDO.getId()));
        request.setUpdater(addressSDO.getUpdater());
        request.setGmtModified(new Date());
        Integer count = 0;
        try {
            UpdateCustomerAddressResponse response = customerAddressService.updateCustomerAddress(request);
            count = response.getCount();
            if (count == 0) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("数据更新失败");
        }
        return true;
    }


    @Override
    public CustomerAddressSDO query(CustomerAddressRequest customerAddressRequest) {
        LoadCustomerAddressRequest loadRequest = new LoadCustomerAddressRequest();
        BeanUtils.copyProperties(customerAddressRequest, loadRequest);
        CustomerAddress customerAddress = customerAddressService.loadCustomerAddress(loadRequest);
        CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
        BeanUtils.copyProperties(customerAddress, customerAddressSDO);
        CustomerAddressSDO addressSDO = setAddressDetailInfo(customerAddressSDO);
        return addressSDO;
    }

    @NotNull
    private CustomerAddressSDO setAddressDetailInfo(CustomerAddressSDO customerAddressSDO) {
        String channelName = "";
        String itemGroupName = "";
        String shippingConditions = "";
        String frozenStatus = "";
        String kunn2 = "";
        String storeHouse = "";
        String parvw = "";
        String transportAreaName = "";
        String regio = "";
        String customerGroup = "";
        String outOrgSalesDepartmentName = "";
        String storeHouseName = "";
        if (!StringUtils.isEmpty(customerAddressSDO.getFeatures())) {
            JSONObject jsonobject = JSONObject.parseObject(customerAddressSDO.getFeatures());
            channelName = jsonobject.getString("channelName");
            itemGroupName = jsonobject.getString("itemGroupName");
            shippingConditions = jsonobject.getString("shippingConditions");
            frozenStatus = jsonobject.getString("frozenStatus");
            kunn2 = jsonobject.getString("kunn2");
            storeHouse = jsonobject.getString("storeHouse");
            parvw = jsonobject.getString("parvw");
            transportAreaName = jsonobject.getString("transportAreaName");
            regio = jsonobject.getString("regio");
            customerGroup = jsonobject.getString("customerGroup");
            outOrgSalesDepartmentName = jsonobject.getString("outOrgSalesDepartmentName");
            storeHouseName = jsonobject.getString("storeHouseName");
        }

        customerAddressSDO.setChannelName(channelName);
        customerAddressSDO.setItemGroupName(itemGroupName);
        customerAddressSDO.setTransportAreaName(transportAreaName);
        if (Objects.isNull(customerAddressSDO.getStatus())) {
            frozenStatus = "禁用";
        } else {
            frozenStatus = customerAddressSDO.getStatus() == 1 ? "启用" : "禁用";
        }
        customerAddressSDO.setFrozenStatus(frozenStatus);
        customerAddressSDO.setShippingConditions(shippingConditions);
        customerAddressSDO.setKunn2(kunn2);
        customerAddressSDO.setStoreHouse(storeHouse);
        customerAddressSDO.setParvw(parvw);
        customerAddressSDO.setRegio(regio);
        customerAddressSDO.setCustomerGroup(customerGroup);
        customerAddressSDO.setOutOrgSalesDepartmentName(outOrgSalesDepartmentName);
        //取渠道名称
        QueryChannelRequest queryChannelRequest = new QueryChannelRequest();
        queryChannelRequest.setChannelCode(customerAddressSDO.getChannelCode());
        Result<ChannelResponse> channelDetail = channelService.queryChannelDetail(queryChannelRequest);
        if (Objects.nonNull(channelDetail) && Objects.nonNull(channelDetail.getResult())) {
            ChannelResponse detailResult = channelDetail.getResult();
            customerAddressSDO.setChannelName(detailResult.getChannelName());
        }
        //取货品组名称
        LoadScItemGroupListRequest listRequest = new LoadScItemGroupListRequest();
        listRequest.setOutCode(customerAddressSDO.getItemGroup());
        Result<List<ScItemGroup>> listResult = scItemGroupService.loadScItemGroupList(listRequest);
        if (CollectionUtils.isNotEmpty(listResult.getResult())) {
            ScItemGroup group = listResult.getResult().stream().findFirst().get();
            customerAddressSDO.setItemGroupName(group.getName());
        }

        //取仓库名称
        if (StringUtils.isNotBlank(storeHouseName)) {
            customerAddressSDO.setStoreHouseName(storeHouseName);
        } else {
            WmsQueryWarehouseZoneListRequest warehouseZoneListRequest = WmsQueryWarehouseZoneListRequest.builder().code(storeHouse).build();
            WmsQueryWarehouseZoneListResponse zoneListResponse = unifiedInventoryService.wmsQueryWarehouseZoneList(warehouseZoneListRequest);
            if (Objects.nonNull(zoneListResponse) && CollectionUtils.isNotEmpty(zoneListResponse.getResult())) {
                WarehouseInfo warehouseInfo = zoneListResponse.getResult().stream().findFirst().get();
                customerAddressSDO.setStoreHouseName(warehouseInfo.getName());
            }

        }
        return customerAddressSDO;
    }

    /**
     * es降级获取客户送达方地址
     * @param request 请求
     * @param commercePlatformCode 电商平台
     * @param addressIds 客户方负责人
     * @return 结果
     */
    private PageQueryCustomerAddressListResponse customerAddressListByDBWhenDegraded(QueryAddressRequest request, String commercePlatformCode, List<Long> addressIds) {
        Integer id = Objects.nonNull(request.getId()) ? Integer.parseInt(request.getId()) : null;
        PageQueryCustomerAddressListResponse pageQueryCustomerAddressListResponse = new PageQueryCustomerAddressListResponse();
        log.info("CustomerAddressRepositoryImpl.customerAddressListForDemoteES.param|request:{},commercePlatformCode:{}, addressIds:{}",JSONObject.toJSONString(request), commercePlatformCode, JSONObject.toJSONString(addressIds));
        if (request.getIsWithPrincipal() == null) {
            CustomerAddressListByDBWhenDegradedRequest customerAddressListRequest = new CustomerAddressListByDBWhenDegradedRequest();
            BeanUtils.copyProperties(request, customerAddressListRequest);
            customerAddressListRequest.setId(id);
            customerAddressListRequest.setCommercePlatform(commercePlatformCode);
            customerAddressListRequest.setIds(addressIds);
            CustomerAddressListByDBWhenDegradedResponse response = customerAddressService.customerAddressListByDBWhenDegraded(customerAddressListRequest);
            if (response != null) {
                pageQueryCustomerAddressListResponse.setResult(response.getResult());
                pageQueryCustomerAddressListResponse.setTotal(response.getTotal());
                pageQueryCustomerAddressListResponse.setSuccess(response.getSuccess());
            }
        } else {
            if (Boolean.TRUE.equals(request.getIsWithPrincipal())) {
                CustomerAddressWithPrincipalListByDBWhenDegradedRequest customerAddressListRequest = new CustomerAddressWithPrincipalListByDBWhenDegradedRequest();
                BeanUtils.copyProperties(request, customerAddressListRequest);
                customerAddressListRequest.setId(id);
                customerAddressListRequest.setCommercePlatform(commercePlatformCode);
                customerAddressListRequest.setIds(addressIds);
                CustomerAddressWithPrincipalListByDBWhenDegradedResponse response = customerAddressService.customerAddressWithPrincipalListByDBWhenDegraded(customerAddressListRequest);
                if (response != null) {
                    pageQueryCustomerAddressListResponse.setResult(response.getResult());
                    pageQueryCustomerAddressListResponse.setTotal(response.getTotal());
                    pageQueryCustomerAddressListResponse.setSuccess(response.getSuccess());
                }
            } else {
                CustomerAddressWithNotPrincipalListByDBWhenDegradedRequest customerAddressListRequest = new CustomerAddressWithNotPrincipalListByDBWhenDegradedRequest();
                BeanUtils.copyProperties(request, customerAddressListRequest);
                customerAddressListRequest.setId(id);
                customerAddressListRequest.setCommercePlatform(commercePlatformCode);
                customerAddressListRequest.setIds(addressIds);
                CustomerAddressWithNotPrincipalListByDBWhenDegradedResponse response = customerAddressService.customerAddressWithNotPrincipalListByDBWhenDegraded(customerAddressListRequest);
                if (response != null) {
                    pageQueryCustomerAddressListResponse.setResult(response.getResult());
                    pageQueryCustomerAddressListResponse.setTotal(response.getTotal());
                    pageQueryCustomerAddressListResponse.setSuccess(response.getSuccess());
                }
            }
        }
        return pageQueryCustomerAddressListResponse;
    }

    /**
     * 通过es获取客户送达方地址
     * @param request 请求
     * @param commercePlatformCode 电商平台
     * @param addressIds 客户方负责人
     * @return 结果
     */
    private PageQueryCustomerAddressListResponse customerAddressListByEs(QueryAddressRequest request, String commercePlatformCode, List<Long> addressIds) {
        Integer id = Objects.nonNull(request.getId()) ? Integer.parseInt(request.getId()) : null;
        PageQueryCustomerAddressListResponse pageQueryCustomerAddressListResponse = new PageQueryCustomerAddressListResponse();
        if (request.getIsWithPrincipal() == null) {
            PageQueryCustomerAddressListRequest customerAddressListRequest = new PageQueryCustomerAddressListRequest();
            BeanUtils.copyProperties(request, customerAddressListRequest);
            customerAddressListRequest.setId(id);
            customerAddressListRequest.setCommercePlatform(commercePlatformCode);
            customerAddressListRequest.setIds(addressIds);
            pageQueryCustomerAddressListResponse = addressIndexService.pageQueryCustomerAddressList(customerAddressListRequest);
        } else {
            if (Boolean.TRUE.equals(request.getIsWithPrincipal())) {
                PageQueryCustomerAddressListWithPrincipalRequest customerAddressListRequest = new PageQueryCustomerAddressListWithPrincipalRequest();
                BeanUtils.copyProperties(request, customerAddressListRequest);
                customerAddressListRequest.setId(id);
                customerAddressListRequest.setCommercePlatform(commercePlatformCode);
                customerAddressListRequest.setIds(addressIds);
                PageQueryCustomerAddressListWithPrincipalResponse response = addressIndexService.pageQueryCustomerAddressListWithPrincipal(customerAddressListRequest);
                if (null != response) {
                    pageQueryCustomerAddressListResponse.setResult(response.getResult());
                    pageQueryCustomerAddressListResponse.setTotal(response.getTotal());
                    pageQueryCustomerAddressListResponse.setSuccess(response.getSuccess());
                }
            } else {
                PageQueryCustomerAddressListNotPrincipalRequest customerAddressListRequest = new PageQueryCustomerAddressListNotPrincipalRequest();
                BeanUtils.copyProperties(request, customerAddressListRequest);
                customerAddressListRequest.setId(id);
                customerAddressListRequest.setCommercePlatform(commercePlatformCode);
                customerAddressListRequest.setIds(addressIds);
                PageQueryCustomerAddressListNotPrincipalResponse response = addressIndexService.pageQueryCustomerAddressListNotPrincipal(customerAddressListRequest);
                if (null != response) {
                    pageQueryCustomerAddressListResponse.setResult(response.getResult());
                    pageQueryCustomerAddressListResponse.setTotal(response.getTotal());
                    pageQueryCustomerAddressListResponse.setSuccess(response.getSuccess());
                }
            }
        }
        return pageQueryCustomerAddressListResponse;
    }

    @Override
    @RepositoryInvoker
    public PageResult<List<CustomerAddressSDO>> pageQuery(QueryAddressRequest request) {
        log.error("CustomerAddressQueryServiceImpl_pageQuery_request："+JSONObject.toJSONString(request));

        // Integer id = Objects.nonNull(request.getId())?Integer.parseInt(request.getId()):null;

        //查询条件 电商平台
        String commercePlatformCode = null;
        if (StringUtils.isNotBlank(request.getCommercePlatform())){
            List<PlatformSDO> result = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformIds(Lists.newArrayList(request.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(result)){
                for (PlatformSDO platformSDO : result) {
                    commercePlatformCode = platformSDO.getPlatformCode();
                }
            }
        }

        //查询条件 客户方负责人
        List<Long> addressIds = null;
        if (StringUtils.isNotBlank(request.getCustomerPrincipal())){
            List<CustomerAddressRelationSDO> result = customerAddressRelationRepository.queryRelationList(CustomerAddressRelationLoadListRequest.newCustomerAddressRelationLoadListRequestBuilder()
                    .relationId(request.getCustomerPrincipal())
                    .bizType(CustomerRelationBizTypeEnum.ADDRESS_CUSTOMER_PRINCIPAL_RELATION.getValue())
                    .build());
            if (CollectionUtils.isNotEmpty(result)){
                addressIds = result.stream().map(x->Long.valueOf(x.getAddressId())).collect(Collectors.toList());
            }
            if (CollectionUtils.isEmpty(addressIds)){
                return PageResult.empty();
            }
            request.setCustomerPrincipal(null);
        }

        PageQueryCustomerAddressListResponse pageQueryCustomerAddressListResponse = new PageQueryCustomerAddressListResponse();

        // es降级开关 若开关开启，需要走db降级查询 开关未开启，走原有逻辑
        GetEsDegradeValueResponse degradeValueResponse = esDegradeService.getEsDegradeValue();
        if (Objects.nonNull(degradeValueResponse) && degradeValueResponse.getResult()) {
            log.info("customerAddressListForDemoteES");
            pageQueryCustomerAddressListResponse = customerAddressListByDBWhenDegraded(request, commercePlatformCode, addressIds);
        } else {
            // 原有链路
            pageQueryCustomerAddressListResponse = customerAddressListByEs(request, commercePlatformCode, addressIds);
        }

        if (Objects.isNull(pageQueryCustomerAddressListResponse) || CollectionUtils.isEmpty(pageQueryCustomerAddressListResponse.getResult())) {
            return PageResult.of(Lists.newArrayList(), 0);
        }
        List<CustomerAddressIndex> customerAddressList = pageQueryCustomerAddressListResponse.getResult();

        //查询结果转换下组织名称
        Set<String> orgSaleOrgCodes = customerAddressList.stream().map(CustomerAddressIndex::getOrgSaleOrganizationCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSaleChannelCodes = customerAddressList.stream().map(CustomerAddressIndex::getOrgSaleChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSaleDepartmentCodes = customerAddressList.stream().map(CustomerAddressIndex::getOrgSaleDepartmentCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> codes = Sets.newHashSet();
        codes.addAll(orgSaleOrgCodes);
        codes.addAll(orgSaleChannelCodes);
        codes.addAll(orgSaleDepartmentCodes);
        BaselineGetOrganizationByIdsAllRequest byIds2Request = BaselineGetOrganizationByIdsAllRequest.builder().ids(Lists.newArrayList(codes)).build();
        BaselineGetOrganizationByIdsAllResponse byIds2Response = baseDataService.baselineGetOrganizationByIdsAll(byIds2Request);
        Map<String, OrganizationSDO> organizationSDOMap = Maps.newHashMap();
        if (Objects.nonNull(byIds2Response) && CollectionUtils.isNotEmpty(byIds2Response.getResult())) {
            organizationSDOMap = byIds2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
        }
        Map<String, OrganizationSDO> finalOrganizationSDOMap = organizationSDOMap;

        //查询结果转换下负责人名称
        Set<String> persons = customerAddressList.stream().map(CustomerAddressIndex::getPrincipal).collect(Collectors.toSet());
        Set<String> customerPersons = customerAddressList.stream().map(CustomerAddressIndex::getCustomerPrincipal).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> creators = customerAddressList.stream().map(it -> it.getCreator().replace("CZ_", "")).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> updaters = customerAddressList.stream().map(it -> it.getUpdater().replace("CZ_", "")).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        persons.addAll(creators);
        persons.addAll(updaters);
        persons.addAll(customerPersons);
        BaselineGetEmployeeByIdsAllRequest byIdsRequest = BaselineGetEmployeeByIdsAllRequest.builder().ids(Lists.newArrayList(persons)).build();
        Result<List<EmployeeSDO>> listResult = baseDataService.baselineGetEmployeeByIdsAll(byIdsRequest);
        Map<String, EmployeeSDO> employeeSDOMap = Maps.newHashMap();
        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
            List<EmployeeSDO> employeeSDOS = listResult.getResult();
            employeeSDOMap = employeeSDOS.stream().collect(Collectors.toMap(EmployeeSDO::getId, o -> o));
        }
        Map<String, EmployeeSDO> finalEmployeeSDOMap = employeeSDOMap;

        //查询结果转换下客户名称
//        Set<String> customerCodes = customerAddressList.stream().map(CustomerAddressIndex::getCustomerCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
//        CustomerBatchRequest customerBatchRequest = CustomerBatchRequest.builder().codes(Lists.newArrayList(customerCodes)).build();
//        List<CustomerSDO> customerSDOS = customerRepository.batchQuery(customerBatchRequest);
//        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
//        if (CollectionUtils.isNotEmpty(customerSDOS)) {
//            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
//        }
//        Map<String, CustomerSDO> finalCustomerSDOMap = customerSDOMap;

        //查询结果转换下业务渠道名称
        Set<String> channelCodes = customerAddressList.stream().map(CustomerAddressIndex::getChannelCode).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        BaselineBatchQueryChannels2Request queryChannels2Request = BaselineBatchQueryChannels2Request.builder().channelCodes(Lists.newArrayList(channelCodes)).build();
        Result<List<ChannelSDO>> channelSDOS = baseDataService.baselineBatchQueryChannels2(queryChannels2Request);
        Map<String, ChannelSDO> channelSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(channelSDOS.getResult())) {
            channelSDOMap = channelSDOS.getResult().stream().collect(Collectors.toMap(ChannelSDO::getChannelCode, o -> o));
        }
        Map<String, ChannelSDO> finalChannelSDOMap = channelSDOMap;

        //查询结果转换下电商平台名称
        Map<String, PlatformSDO> platformSDOMap = Maps.newHashMap();
        Set<String> commercePlatforms = customerAddressList.stream().map(CustomerAddressIndex::getCommercePlatform).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        if(CollectionUtils.isNotEmpty(commercePlatforms)){
            BaselineBatchQueryPlatforms2Request queryPlatforms2Request = BaselineBatchQueryPlatforms2Request.builder().platformCodes(Lists.newArrayList(commercePlatforms)).build();
            Result<List<PlatformSDO>> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(queryPlatforms2Request);
            if (CollectionUtils.isNotEmpty(platformSDOS.getResult())) {
                platformSDOMap = platformSDOS.getResult().stream().collect(Collectors.toMap(PlatformSDO::getPlatformCode, o -> o));
            }
        }
        Map<String, PlatformSDO> finalPlatformSDOMap = platformSDOMap;

        //货品组名称,当前SAP货品组只有1个货品租
        Set<String> itemGroups = customerAddressList.stream().map(CustomerAddressIndex::getItemGroup).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        List<String> itemGroupList = Lists.newArrayList(itemGroups);
        if(CollectionUtils.isNotEmpty(itemGroupList) && itemGroupList.size()>1){
            log.info("CustomerAddressQueryServiceImpl_pageQuery_pageItemGroup_size={}",itemGroupList.size());
        }
        LoadScItemGroupListRequest itemGroupListRequest = LoadScItemGroupListRequest.builder().code(itemGroupList.get(0)).build();
        Result<List<ScItemGroup>> itemGroupResult = scItemGroupService.loadScItemGroupList(itemGroupListRequest);
        ScItemGroup scItemGroup = new ScItemGroup();
        if(CollectionUtils.isNotEmpty(itemGroupResult.getResult())){
            scItemGroup = itemGroupResult.getResult().stream().findFirst().get();
        }
        ScItemGroup finalScItemGroup = scItemGroup;

        //客户方负责人
        Map<String, List<CustomerAddressRelationSDO>> customerAddressRelationMap = Maps.newHashMap();
        Set<String> ids = customerAddressList.stream().map(x-> String.valueOf(x.getId())).collect(Collectors.toSet());
        CustomerAddressRelationLoadListRequest relationLoadListRequest = new CustomerAddressRelationLoadListRequest();
        relationLoadListRequest.setAddressIds(Lists.newArrayList(ids));
        relationLoadListRequest.setBizType(CustomerRelationBizTypeEnum.ADDRESS_CUSTOMER_PRINCIPAL_RELATION.getValue());
        List<CustomerAddressRelationSDO> relationResult = customerAddressRelationRepository.queryRelationList(relationLoadListRequest);
        if (CollectionUtils.isNotEmpty(relationResult)) {
            customerAddressRelationMap = relationResult.stream().collect(Collectors.groupingBy(CustomerAddressRelationSDO::getAddressId));
        }
        Map<String, List<CustomerAddressRelationSDO>> finalCustomerAddressRelationMap = customerAddressRelationMap;

        List<CustomerAddressSDO> resultList = customerAddressList.stream().map(address -> {
            CustomerAddressSDO addressSDO = new CustomerAddressSDO();
            BeanUtils.copyProperties(address, addressSDO);
            addressSDO.setId(address.getId().toString());
            if (!StringUtils.isEmpty(address.getFeatures())) {
                JSONObject jsonobject = JSONObject.parseObject(address.getFeatures());
                String itemGroupName = jsonobject.getString("itemGroupName");
                String shippingConditions = jsonobject.getString("shippingConditions");
                String frozenStatus = jsonobject.getString("frozenStatus");
                String kunn2 = jsonobject.getString("kunn2");
                String storeHouse = jsonobject.getString("storeHouse");
                String parvw = jsonobject.getString("parvw");
                String transportAreaName = jsonobject.getString("transportAreaName");
                String customerGroup = jsonobject.getString("customerGroup");
                String transportArea = jsonobject.getString("transportArea");
                String outOrgSalesDepartmentCode = jsonobject.getString("outOrgSalesDepartmentCode");
                String outOrgSalesDepartmentName = jsonobject.getString("outOrgSalesDepartmentName");
                String outOrgSalesChannelCode = jsonobject.getString("outOrgSalesChannelCode");
                String outOrgSalesChannelName = jsonobject.getString("outOrgSalesChannelName");
                String regio = jsonobject.getString("regio");
                addressSDO.setItemGroupName(itemGroupName);
                addressSDO.setTransportAreaName(transportAreaName);
                addressSDO.setFrozenStatus(frozenStatus);
                addressSDO.setShippingConditions(shippingConditions);
                addressSDO.setKunn2(kunn2);
                addressSDO.setStoreHouse(storeHouse);
                addressSDO.setParvw(parvw);
                addressSDO.setCustomerGroup(customerGroup);
                addressSDO.setTransportArea(transportArea);
                addressSDO.setOutOrgSalesDepartmentCode(outOrgSalesDepartmentCode);
                addressSDO.setOutOrgSalesDepartmentName(outOrgSalesDepartmentName);
                addressSDO.setRegio(regio);
                addressSDO.setGmtCreate(address.getGmt_create());
                addressSDO.setGmtModified(address.getGmt_modified());
                addressSDO.setOutOrgSalesChannelCode(outOrgSalesChannelCode);
                addressSDO.setOutOrgSalesChannelName(outOrgSalesChannelName);
            }

            //组织名称
            OrganizationSDO orgSaleOrganization = finalOrganizationSDOMap.get(address.getOrgSaleOrganizationCode());
            if(Objects.nonNull(orgSaleOrganization)){
                addressSDO.setOrgSalesOrganizationName(orgSaleOrganization.getName());
                addressSDO.setOrgSalesOrganizationCode2(orgSaleOrganization.getCode());
            }
            OrganizationSDO orgSaleChannel = finalOrganizationSDOMap.get(address.getOrgSaleChannelCode());
            if(Objects.nonNull(orgSaleChannel)) {
                addressSDO.setOrgSalesChannelName(orgSaleChannel.getName());
                addressSDO.setOrgSalesChannelCode2(orgSaleChannel.getCode());
            }
            OrganizationSDO orgSaleDepartment = finalOrganizationSDOMap.get(address.getOrgSaleDepartmentCode());
            if(Objects.nonNull(orgSaleDepartment)) {
                addressSDO.setOrgSalesDepartmentName(orgSaleDepartment.getName());
                addressSDO.setOrgSalesDepartmentCode2(orgSaleDepartment.getCode());
            }

            EmployeeSDO creator = finalEmployeeSDOMap.get(address.getCreator().replace("CZ_", ""));
            if (Objects.nonNull(creator)) {
                addressSDO.setCreatorName(creator.getName());
            }
            EmployeeSDO updater = finalEmployeeSDOMap.get(address.getUpdater().replace("CZ_", ""));
            if (Objects.nonNull(updater)) {
                addressSDO.setUpdaterName(updater.getName());
            }
            //负责人
            EmployeeSDO employeeSDO = finalEmployeeSDOMap.get(address.getPrincipal());
            if (Objects.nonNull(employeeSDO)) {
                addressSDO.setPrincipalName(employeeSDO.getName());
                addressSDO.setNick(employeeSDO.getNick());
            }
            EmployeeSDO customerEmp = finalEmployeeSDOMap.get(address.getCustomerPrincipal());
            if (Objects.nonNull(customerEmp)) {
                addressSDO.setCustomerPrincipalName(customerEmp.getName());
            }
            //客户名称
//            CustomerSDO customerSDO = finalCustomerSDOMap.get(address.getCustomerCode());
//            if (Objects.nonNull(customerSDO)) {
//                addressSDO.setCustomerName(customerSDO.getName());
//            }
            //渠道名称
            ChannelSDO channelSDO = finalChannelSDOMap.get(address.getChannelCode());
            if (Objects.nonNull(channelSDO)) {
                addressSDO.setChannelName(channelSDO.getChannelName());
            }
            //平台名称
            PlatformSDO platformSDO = finalPlatformSDOMap.get(address.getCommercePlatform());
            if (Objects.nonNull(platformSDO)) {
                addressSDO.setCommercePlatform(platformSDO.getPlatformName());
            }
            //货品组名称
            if(StringUtils.isNotBlank(address.getItemGroup())){
                addressSDO.setItemGroupName(finalScItemGroup.getName());
            }

            //客户方负责人
            addressSDO.setCustomerPrincipalName("");
            List<CustomerAddressRelationSDO> relationList = finalCustomerAddressRelationMap.get(addressSDO.getId());
            if(CollectionUtils.isNotEmpty(relationList)){
                String str = relationList.stream().map(CustomerAddressRelationSDO::getRelationName).collect(Collectors.toList()).toString();
                String empIdLIstStr = relationList.stream().map(CustomerAddressRelationSDO::getRelationId).collect(Collectors.joining(","));
                addressSDO.setCustomerPrincipalName(str.substring(1,str.length()-1));
                List<String> list = relationList.stream().map(x-> {
                    String featuresString = x.getFeatures();
                    if(StringUtils.isNotBlank(featuresString)){
                        return (String)JSONObject.parseObject(featuresString,Map.class).get("nick");
                    }
                    return null;
                }).collect(Collectors.toList());
                String str2 = list.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList()).toString();
                addressSDO.setCustomerPrincipalNick(str2.substring(1,str2.length()-1));
                addressSDO.setCustomerPrincipal(empIdLIstStr);
            }
            return addressSDO;
        }).collect(Collectors.toList());

        return PageResult.of(resultList, pageQueryCustomerAddressListResponse.getTotal());
    }

    @Override
    public PageResult<List<CustomerAddressSDO>> simplePageQuery(SimpleQueryAddressRequest request) {
        PageQueryCustomerAddressListRequest queryAddressListRequest = new PageQueryCustomerAddressListRequest();
        queryAddressListRequest.setOrgBussinessUnitCode(request.getOrgBussinessUnitCode());
        queryAddressListRequest.setOrgSaleOrganizationCode(request.getOrgSaleOrganizationCode());
        queryAddressListRequest.setOrgSaleChannelCode(request.getOrgSaleChannelCode());
        queryAddressListRequest.setOrgSaleDepartmentCode(request.getOrgSaleDepartmentCode());
        queryAddressListRequest.setStatus(request.getStatus());
        queryAddressListRequest.setStart(request.getStart());
        queryAddressListRequest.setLimit(request.getLimit());
        PageQueryCustomerAddressListResponse response = addressIndexService.pageQueryCustomerAddressList(queryAddressListRequest);
        if (Objects.isNull(response) || CollectionUtils.isEmpty(response.getResult())) {
            return PageResult.of(Lists.newArrayList(), 0);
        }

        List<CustomerAddressSDO> resultList = response.getResult().stream().map(x -> {
            CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
            customerAddressSDO.setId(x.getId().toString());
            customerAddressSDO.setAddressCode(x.getAddressCode());
            customerAddressSDO.setAddressName(x.getAddressName());
            customerAddressSDO.setCustomerCode(x.getCustomerCode());
            customerAddressSDO.setCustomerName(x.getCustomerName());
            customerAddressSDO.setOrgBussinessUnitCode(x.getOrgBussinessUnitCode());
            customerAddressSDO.setOrgSaleOrganizationCode(x.getOrgSaleOrganizationCode());
            customerAddressSDO.setOrgSaleChannelCode(x.getOrgSaleChannelCode());
            customerAddressSDO.setOrgSaleDepartmentCode(x.getOrgSaleDepartmentCode());
            customerAddressSDO.setChannelCode(x.getChannelCode());
            return customerAddressSDO;
        }).collect(Collectors.toList());
        return  PageResult.of(resultList, response.getTotal());
    }

    @Override
    @RepositoryInvoker
    public List<CustomerAddressSDO> batchQuery(CustomerAddressBatchRequest request) {
        BatchQueryRequest batchQueryRequest = new BatchQueryRequest();
        BeanUtils.copyProperties(request, batchQueryRequest);
        BatchQueryResponse response = customerAddressService.batchQuery(batchQueryRequest);
        if (response == null || CollectionUtils.isEmpty(response.getResult())) {
            return null;
        }
        List<CustomerAddressSDO> result = Lists.newArrayList();
        List<CustomerAddress> customerAddressList = response.getResult();
        Set<String> codeSet = customerAddressList.stream().map(CustomerAddress::getCustomerCode).collect(Collectors.toSet());
        CustomerBatchRequest customerBatchRequest = new CustomerBatchRequest();
        customerBatchRequest.setCodes(Lists.newArrayList(codeSet));
        List<CustomerSDO> customerSDOS = customerRepository.batchQuery(customerBatchRequest);
        Map<String, CustomerSDO> customerSDOMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(customerSDOS)) {
            customerSDOMap = customerSDOS.stream().collect(Collectors.toMap(CustomerSDO::getCode, o -> o));
        }
        Set<String> orgCodes = customerAddressList.stream().map(CustomerAddress::getOrgSaleOrganizationCode).filter(
                StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> salesChannelCodes = customerAddressList.stream().map(CustomerAddress::getOrgSaleChannelCode).filter(
                StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> departCodes = customerAddressList.stream().map(CustomerAddress::getOrgSaleDepartmentCode).filter(
                StringUtils::isNotBlank).collect(Collectors.toSet());
        HashSet<String> codes = Sets.newHashSet();
        codes.addAll(orgCodes);
        codes.addAll(salesChannelCodes);
        codes.addAll(departCodes);
        BaselineGetOrganizationByIds2Request byIds2Request = BaselineGetOrganizationByIds2Request.builder().ids(Lists.newArrayList(codes)).status(1).build();
        BaselineGetOrganizationByIds2Response byIds2Response = baseDataService.baselineGetOrganizationByIds2(byIds2Request);
        Map<String, OrganizationSDO> organizationSDOMap = Maps.newHashMap();
        if (Objects.nonNull(byIds2Response) && CollectionUtils.isNotEmpty(byIds2Response.getResult())) {
            organizationSDOMap = byIds2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getId, o -> o));
        }

        for (CustomerAddress address : customerAddressList) {
            CustomerAddressSDO addressSDO = new CustomerAddressSDO();
            BeanUtils.copyProperties(address, addressSDO);
            addressSDO.setId(String.valueOf(address.getId()));
            CustomerSDO customerSDO = customerSDOMap.get(address.getCustomerCode());
            if (Objects.nonNull(customerSDO)) {
                addressSDO.setCustomerName(customerSDO.getName());
            }
            OrganizationSDO orgSDO = organizationSDOMap.get(address.getOrgSaleOrganizationCode());
            if (Objects.nonNull(orgSDO)) {
                addressSDO.setOrgSalesOrganizationName(orgSDO.getName());
            }
            OrganizationSDO channelSDO = organizationSDOMap.get(address.getOrgSaleChannelCode());
            if (Objects.nonNull(channelSDO)) {
                addressSDO.setOrgSalesChannelName(channelSDO.getName());
            }
            OrganizationSDO departSDO = organizationSDOMap.get(address.getOrgSaleDepartmentCode());
            if (Objects.nonNull(departSDO)) {
                addressSDO.setOrgSalesDepartmentName(departSDO.getName());
            }
            result.add(addressSDO);
        }
        return result;
    }

    @Override
    @RepositoryInvoker
    public Integer queryAddressPrincipalCount(FullOrganizationValue fullOrganizationValue, List<String> employeeIdList) {
        QueryAddressPrincipalCountRequest request = new QueryAddressPrincipalCountRequest();
        request.setOrgBussinessUnitCode(fullOrganizationValue.getOrgBusinessUnitCode());
        request.setOrgSaleOrganizationCode(fullOrganizationValue.getOrgSalesOrganizationCode());
        request.setOrgSaleChannelCode(fullOrganizationValue.getOrgSalesChannelCode());
        request.setOrgSaleDepartmentCode(fullOrganizationValue.getOrgSalesDepartmentCode());
        if (CollectionUtils.isNotEmpty(employeeIdList)) {
            request.setEmployeeIdList(employeeIdList);
        }
        QueryAddressPrincipalCountResponse response = customerAddressService.queryAddressPrincipalCount(request);
        if (response != null) {
            return response.getCount();
        }
        return null;
    }

    @Override
    @RepositoryInvoker
    public List<String> queryAddressPrincipalList(FullOrganizationValue fullOrganizationValue, List<String> employeeIdList) {
        QueryAddressPrincipalRequest request = new QueryAddressPrincipalRequest();
        request.setOrgBussinessUnitCode(fullOrganizationValue.getOrgBusinessUnitCode());
        request.setOrgSaleOrganizationCode(fullOrganizationValue.getOrgSalesOrganizationCode());
        request.setOrgSaleChannelCode(fullOrganizationValue.getOrgSalesChannelCode());
        request.setOrgSaleDepartmentCode(fullOrganizationValue.getOrgSalesDepartmentCode());
        request.setStart(fullOrganizationValue.getStart());
        request.setLimit(fullOrganizationValue.getLimit());
        if (CollectionUtils.isNotEmpty(employeeIdList)) {
            request.setEmployeeIdList(employeeIdList);
        }
        QueryAddressPrincipalResponse response = customerAddressService.queryAddressPrincipal(request);
        if (response != null) {
            return response.getResult();
        }
        return null;
    }

    @Override
    @RepositoryInvoker
    public CustomerAddressSDO load(String id) {
        LoadCustomerAddresRequest loadRequest = new LoadCustomerAddresRequest();
        loadRequest.setId(id);
        CustomerAddress customerAddress = new CustomerAddress();
        try {
            log.error("wyd.loadRequest=" + JSONObject.toJSONString(loadRequest));
            customerAddress = customerAddressService.loadCustomerAddres(loadRequest);
            log.error("wyd.customerAddress=" + JSONObject.toJSONString(customerAddress));
        } catch (Exception e) {
            log.error("customerAddress.load.error=" + JSONObject.toJSONString(e));
            return null;
        }
        CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
        BeanUtils.copyProperties(customerAddress, customerAddressSDO);
        //电商平台
        queryCommercePlatform(customerAddressSDO);
        customerAddressSDO.setId(String.valueOf(customerAddress.getId()));
        return customerAddressSDO;
    }

    private void queryCommercePlatform(CustomerAddressSDO customerAddressSDO) {
        //根据当前数据的平台Code去获取对应的名称
        if (StringUtils.isNotBlank(customerAddressSDO.getCommercePlatform())) {
            List<PlatformSDO> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(BaselineBatchQueryPlatforms2Request.builder().platformCodes(Lists.newArrayList(customerAddressSDO.getCommercePlatform())).build()).getResult();
            if (CollectionUtils.isNotEmpty(platformSDOS)) {
                String platformName = platformSDOS.get(0).getPlatformName();
                customerAddressSDO.setCommercePlatform(platformName);
            }
        }
       /* try{
        BaselineGetOrganizationByIdsAllRequest byIdsAllRequest = new BaselineGetOrganizationByIdsAllRequest();
        if (StringUtils.isBlank(customerAddressSDO.getOrgSaleDepartmentCode())){
            return;
        }
        byIdsAllRequest.setIds(Lists.newArrayList(customerAddressSDO.getOrgSaleDepartmentCode()));
        List<OrganizationSDO> result = baseDataService.baselineGetOrganizationByIdsAll(byIdsAllRequest).getResult();
        if (CollectionUtils.isEmpty(result)){
            log.info("queryCommercePlatform"+customerAddressSDO.getOrgSaleDepartmentCode());
            return;
        }
        Set<String> platformId = result.stream().map(OrganizationSDO::getPlatformId).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        BaselineBatchQueryPlatforms2Request platforms2Request = new BaselineBatchQueryPlatforms2Request();
        platforms2Request.setPlatformIds(Lists.newArrayList(platformId));
        List<PlatformSDO> platformSDOS = baseDataService.baselineBatchQueryPlatforms2(platforms2Request).getResult();
        platformSDOS.stream().forEach(it->{
            customerAddressSDO.setCommercePlatform(it.getPlatformName());
        });
        }catch (Exception e){
            log.error("queryCommercePlatform失败");
            return;
        }*/
    }

    @Override
    @RepositoryInvoker
    public Result<List<CustomerAddress>> pageQueryCustomerAddressData(CustomerItemPriceRequest customerItemPriceRequest) {
        PageQueryCustomerAddressDataRequest addressDataRequest = new PageQueryCustomerAddressDataRequest();
        addressDataRequest.setCustomerAddressCode(customerItemPriceRequest.getCustomerSendCode());
        addressDataRequest.setSalesOrganizationCode(customerItemPriceRequest.getSaleOrganizationCode());
        addressDataRequest.setChannelCode(customerItemPriceRequest.getChannelCode());
        addressDataRequest.setStart(customerItemPriceRequest.getStart());
        addressDataRequest.setLimit(customerItemPriceRequest.getLimit());
        addressDataRequest.setStatus(CommOperateTypeEnum.ENABLE.getCode());
        PageQueryCustomerAddressDataResponse customerAddressDataResponse = customerAddressService.pageQueryCustomerAddressData(addressDataRequest);

        //参数封装
        Result<List<CustomerAddress>> result = Result.success(customerAddressDataResponse.getResult());
        result.setTotal(customerAddressDataResponse.getTotal());
        return result;
    }
}
